package com.guohang.ESProject08;

import java.util.ArrayList;
import java.util.List;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;


//handles database access from application on top of sqlitehelper class
public class CommentsDataSource {

  // Database fields
  private SQLiteDatabase database;
  private MySQLiteHelper dbHelper;
  private String[] allColumns = {MySQLiteHelper.COLUMN_CAPTURE, MySQLiteHelper.COLUMN_IMAGE, 
		  MySQLiteHelper.COLUMN_TEXT,  MySQLiteHelper.COLUMN_SENSOR_TEMP,  MySQLiteHelper.COLUMN_SENSOR_GSR,  MySQLiteHelper.COLUMN_SENSOR_HEARTRATE,
		  MySQLiteHelper.COLUMN_SENSOR_SOCIAL};

  public CommentsDataSource(Context context) {
    dbHelper = new MySQLiteHelper(context);
  }

  public void open() throws SQLException {
    database = dbHelper.getWritableDatabase();
  }

  public void close() {
    dbHelper.close();
  }

 
  
  public void insertCapture(String text, String imgPath, double temperature, double GSR, double heartRate, double social){
	  
	  //update database table with a new capture
      // together with the capture's image, text, whatever
	 
	  ContentValues values = new ContentValues();
	  values.put(MySQLiteHelper.COLUMN_TEXT, text);
	  values.put(MySQLiteHelper.COLUMN_IMAGE, imgPath);
	  values.put(MySQLiteHelper.COLUMN_SENSOR_TEMP, temperature);
	  values.put(MySQLiteHelper.COLUMN_SENSOR_GSR, GSR);
	  values.put(MySQLiteHelper.COLUMN_SENSOR_HEARTRATE, heartRate);
	  values.put(MySQLiteHelper.COLUMN_SENSOR_SOCIAL, social);

	  long insertId = database.insert(MySQLiteHelper.TABLE_NAME, null, values);		
	  
  }
  
  public List<Capture> getAll(){
	  List<Capture> story = new ArrayList<Capture>();
	  
	  Cursor cursor = database.query(MySQLiteHelper.TABLE_NAME,
		        allColumns, null, null, null, null, null);

      cursor.moveToFirst();
      while (!cursor.isAfterLast()) {
    	  Capture capture = new Capture();

    	  capture.setCapture(cursor.getInt(0));
    	  capture.setText(cursor.getString(2));
    	  capture.setPath(cursor.getString(1));
    	  capture.setTemp(cursor.getDouble(3));
    	  capture.setGSR(cursor.getDouble(4));
    	  capture.setHR(cursor.getDouble(5));
    	  capture.setSocial(cursor.getDouble(6));
    	  
          story.add(capture);
		  cursor.moveToNext();   
		    }

	 	    // Make sure to close the cursor
		    cursor.close();
		    return story;
  }
  
  public void deleteTable(){
	  database.delete(MySQLiteHelper.TABLE_NAME, null, null);
  }
  
 
} 